<template>
  <div class="floor-plan-container">
    <h1 class="floor-plan-title">博物馆内部平面图指引</h1>

    <!-- 分区选择器 -->
    <div class="area-selector">
      <el-radio-group v-model="currentAreaId" @change="handleAreaChange" class="area-tabs">
        <el-radio-button
          v-for="area in museumStore.floorPlanInfo.areas"
          :key="area.id"
          :label="area.id"
        >
          {{ area.name }}
        </el-radio-button>
      </el-radio-group>

      <!-- 管理员控制按钮 -->
      <div v-if="userStore.isAdmin()" class="area-admin-controls">
        <el-button type="success" size="small" @click="openAddAreaDialog">
          <el-icon><Plus /></el-icon> 添加分区
        </el-button>
        <el-button
          v-if="museumStore.floorPlanInfo.areas.length > 1"
          type="danger"
          size="small"
          @click="confirmDeleteArea"
        >
          <el-icon><Delete /></el-icon> 删除分区
        </el-button>
      </div>
    </div>

    <div class="floor-plan-content">
      <!-- 分区图片展示区 -->
      <div class="floor-plan-image-container">
        <div v-if="currentArea && currentArea.image" class="image-wrapper">
          <img :src="currentArea.image" :alt="`${currentArea.name}平面图`" class="floor-plan-image" />
        </div>
        <div v-else class="no-image">
          <el-icon><Picture /></el-icon>
          <span>暂无平面图</span>
        </div>

        <!-- 管理员上传图片按钮 -->
        <div v-if="userStore.isAdmin()" class="admin-controls">
          <el-upload
            class="upload-container"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <el-button type="primary" class="upload-button">
              <el-icon><Upload /></el-icon>
              {{ currentArea && currentArea.image ? '更换平面图' : '上传平面图' }}
            </el-button>
          </el-upload>
        </div>
      </div>

      <!-- 分区信息展示区 -->
      <div class="floor-plan-info">
        <div class="info-header">
          <h2>{{ currentArea ? currentArea.name : '' }}分区导览</h2>
          <el-button
            v-if="userStore.isAdmin() && !isEditing"
            type="primary"
            @click="startEditing"
            class="edit-button"
          >
            <el-icon><Edit /></el-icon> 编辑信息
          </el-button>
        </div>

        <!-- 查看模式 -->
        <div v-if="!isEditing && currentArea" class="info-content">
          <div class="info-item">
            <h3><el-icon><Location /></el-icon> 主要分区</h3>
            <p>{{ currentArea.mainAreas }}</p>
          </div>
          <div class="info-item">
            <h3><el-icon><Guide /></el-icon> 参观路线</h3>
            <p>{{ currentArea.visitRoute }}</p>
          </div>
          <div class="info-item">
            <h3><el-icon><InfoFilled /></el-icon> 分区详情</h3>
            <p>{{ currentArea.areaDetails }}</p>
          </div>
        </div>

        <!-- 编辑模式 (仅管理员可见) -->
        <div v-else-if="isEditing" class="edit-form">
          <el-form :model="editForm" label-position="top">
            <el-form-item label="分区名称">
              <el-input
                v-model="editForm.name"
                placeholder="请输入分区名称"
              />
            </el-form-item>
            <el-form-item label="主要分区">
              <el-input
                v-model="editForm.mainAreas"
                type="textarea"
                :rows="2"
                placeholder="请输入博物馆主要分区信息"
              />
            </el-form-item>
            <el-form-item label="参观路线">
              <el-input
                v-model="editForm.visitRoute"
                type="textarea"
                :rows="3"
                placeholder="请输入推荐参观路线"
              />
            </el-form-item>
            <el-form-item label="分区详情">
              <el-input
                v-model="editForm.areaDetails"
                type="textarea"
                :rows="4"
                placeholder="请输入各分区详细介绍"
              />
            </el-form-item>
            <div class="form-buttons">
              <el-button @click="cancelEditing">取消</el-button>
              <el-button type="primary" @click="saveChanges">保存</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 添加分区对话框 -->
    <el-dialog
      v-model="showAddAreaDialog"
      title="添加新分区"
      width="500px"
    >
      <el-form :model="newAreaForm" label-position="top">
        <el-form-item label="分区名称" required>
          <el-input v-model="newAreaForm.name" placeholder="请输入分区名称，如：四楼" />
        </el-form-item>
        <el-form-item label="主要分区">
          <el-input
            v-model="newAreaForm.mainAreas"
            type="textarea"
            :rows="2"
            placeholder="请输入该分区的主要区域"
          />
        </el-form-item>
        <el-form-item label="参观路线">
          <el-input
            v-model="newAreaForm.visitRoute"
            type="textarea"
            :rows="2"
            placeholder="请输入该分区的推荐参观路线"
          />
        </el-form-item>
        <el-form-item label="分区详情">
          <el-input
            v-model="newAreaForm.areaDetails"
            type="textarea"
            :rows="3"
            placeholder="请输入该分区的详细介绍"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddAreaDialog = false">取消</el-button>
          <el-button type="primary" @click="addNewArea">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useUserStore } from '../stores/user'
import { useMuseumStore, type Area } from '../stores/museum'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Upload, Edit, Location, InfoFilled, Delete, Plus } from '@element-plus/icons-vue'
import { Guide } from '@element-plus/icons-vue'

// 获取用户和博物馆信息存储
const userStore = useUserStore()
const museumStore = useMuseumStore()

// 当前选中的分区ID
const currentAreaId = ref(museumStore.floorPlanInfo.currentAreaId)

// 计算当前选中的分区信息
const currentArea = computed(() => {
  return museumStore.floorPlanInfo.areas.find(area => area.id === currentAreaId.value)
})

// 编辑状态控制
const isEditing = ref(false)

// 编辑表单数据
const editForm = reactive({
  name: '',
  mainAreas: '',
  visitRoute: '',
  areaDetails: ''
})

// 新分区表单数据
const newAreaForm = reactive({
  name: '',
  mainAreas: '',
  visitRoute: '',
  areaDetails: ''
})

// 对话框控制
const showAddAreaDialog = ref(false)
const showDeleteConfirmDialog = ref(false)

// 处理分区切换
const handleAreaChange = (areaId: string) => {
  museumStore.setCurrentArea(areaId)
}

// 开始编辑
const startEditing = () => {
  if (!currentArea.value) return

  // 复制当前数据到编辑表单
  editForm.name = currentArea.value.name
  editForm.mainAreas = currentArea.value.mainAreas
  editForm.visitRoute = currentArea.value.visitRoute
  editForm.areaDetails = currentArea.value.areaDetails
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
}

// 保存更改
const saveChanges = () => {
  if (!currentArea.value) return

  museumStore.updateFloorPlanInfo(currentAreaId.value, {
    name: editForm.name,
    mainAreas: editForm.mainAreas,
    visitRoute: editForm.visitRoute,
    areaDetails: editForm.areaDetails
  })
  isEditing.value = false
  ElMessage.success('分区导览信息已更新')
}

// 处理图片上传
const handleImageChange = (file: any) => {
  if (!file) return

  // 检查文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件!')
    return
  }

  // 检查文件大小 (限制为2MB)
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return
  }

  // 将图片转换为base64
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    const base64 = reader.result as string
    if (currentArea.value) {
      museumStore.updateFloorPlanImage(currentArea.value.id, base64)
      ElMessage.success('平面图上传成功')
    }
  }
}

// 打开添加分区对话框
const openAddAreaDialog = () => {
  // 重置表单
  newAreaForm.name = ''
  newAreaForm.mainAreas = ''
  newAreaForm.visitRoute = ''
  newAreaForm.areaDetails = ''
  showAddAreaDialog.value = true
}

// 添加新分区
const addNewArea = () => {
  if (!newAreaForm.name) {
    ElMessage.warning('请输入分区名称')
    return
  }

  const newAreaId = museumStore.addArea({
    name: newAreaForm.name,
    image: '',
    mainAreas: newAreaForm.mainAreas,
    visitRoute: newAreaForm.visitRoute,
    areaDetails: newAreaForm.areaDetails
  })

  // 切换到新创建的分区
  currentAreaId.value = newAreaId
  museumStore.setCurrentArea(newAreaId)

  showAddAreaDialog.value = false
  ElMessage.success('新分区添加成功')
}

// 确认删除分区
const confirmDeleteArea = () => {
  if (!currentArea.value) return

  ElMessageBox.confirm(
    `确定要删除分区「${currentArea.value.name}」吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    if (currentArea.value) {
      const result = museumStore.deleteArea(currentArea.value.id)
      if (result) {
        // 更新当前选中的分区ID
        currentAreaId.value = museumStore.floorPlanInfo.currentAreaId
        ElMessage.success('分区已删除')
      }
    }
  }).catch(() => {
    // 取消删除操作
  })
}
</script>

<style lang="scss" scoped>
.floor-plan-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px); /* 减去导航栏的高度 */
  width: 100%;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f5f5;
  background-image:
    radial-gradient(circle at 25px 25px, rgba(139, 90, 43, 0.2) 2%, transparent 0%),
    radial-gradient(circle at 75px 75px, rgba(139, 90, 43, 0.2) 2%, transparent 0%);
  background-size: 100px 100px;
}

.floor-plan-title {
  color: #8b5a2b;
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
  font-family: 'SimSun', serif;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.area-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  padding: 10px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e0d5;

  .area-tabs {
    flex: 1;
  }

  .area-admin-controls {
    display: flex;
    gap: 10px;
    margin-left: 15px;
  }
}

.floor-plan-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;

  @media (min-width: 768px) {
    flex-direction: row;
    align-items: flex-start;
  }
}

.floor-plan-image-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e0d5;
}

.image-wrapper {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #e8e0d5;

  img.floor-plan-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;

    &:hover {
      transform: scale(1.02);
    }
  }
}

.no-image {
  width: 100%;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f9f6f2;
  border-radius: 4px;
  border: 1px dashed #d3c6b0;
  color: #a89070;

  .el-icon {
    font-size: 48px;
    margin-bottom: 10px;
  }
}

.admin-controls {
  margin-top: 15px;
  width: 100%;
  display: flex;
  justify-content: center;

  .upload-button {
    background-color: #8b5a2b;
    border-color: #8b5a2b;

    &:hover {
      background-color: #6d4522;
      border-color: #6d4522;
    }
  }
}

.floor-plan-info {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e0d5;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 2px solid #f0e6d9;
  padding-bottom: 10px;

  h2 {
    color: #8b5a2b;
    font-size: 22px;
    margin: 0;
    font-family: 'SimSun', serif;
  }

  .edit-button {
    background-color: #8b5a2b;
    border-color: #8b5a2b;

    &:hover {
      background-color: #6d4522;
      border-color: #6d4522;
    }
  }
}

.info-content {
  .info-item {
    margin-bottom: 20px;

    h3 {
      color: #8b5a2b;
      font-size: 18px;
      margin-bottom: 8px;
      display: flex;
      align-items: center;
      gap: 8px;
      font-family: 'SimSun', serif;
    }

    p {
      color: #333;
      line-height: 1.6;
      margin: 0;
      text-align: justify;
      padding-left: 26px;
    }
  }
}

.edit-form {
  .el-form-item {
    margin-bottom: 15px;
  }

  .form-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }
}
</style>